<?php

/**
 *
 *
 * @version $Id: MenuWidget.php,v 1.1 2011-05-01 06:59:52 herve Exp $
 * @copyright 2011
 */

class MenuWidget extends CWidget {
	public $items = array ();

	public function run() {
		$items = array ();
		$controller = $this->controller;
		$action = $controller->action;
		foreach ($this->items as $item) {
			if (isset($item['visible']) && !$item['visible']) {
				continue;
			}
			if (!isset($item['items']) || !is_array($item['items']) || count($item['items']) <= 0) {
				continue;
			}

			$item2 = array();
			$item2['label'] = $item['label'];
			$item2['items'] = array();

			foreach ($item['items'] as $subItem){
				if (isset ($subItem['visible']) && !$subItem['visible'])
					continue;

				$i = array ();
				$i['label'] = $subItem['label'];
				if (is_array($subItem['url']))
					$i['url'] = $controller->createUrl($subItem['url'][0], array_splice($subItem['url'], 1));
				else
					$i['url'] = $subItem['url'];
				if (isset ($item['target']))
					$i['target'] = $subItem['target'];

				$pattern = isset ($subItem['pattern']) ? $subItem['pattern'] : $subItem['url'];
				$i['active'] = $this->isActive($pattern, $controller->uniqueID, $action->id);

				$item2['items'][] = $i;
			}

			if (count($item2['items'])) {
				$items[] = $item2;
			}
		}
		$this->render('menu', array (
			'items' => $items
		));
	}

	protected function isActive($pattern, $controllerID, $actionID) {
		if (!is_array($pattern) || !isset ($pattern[0]))
			return false;

		$pattern[0] = trim($pattern[0], '/');
		if (strpos($pattern[0], '/') !== false)
			$matched = $pattern[0] === $controllerID .
			'/' . $actionID;
		else
			$matched = $pattern[0] === $controllerID;

		if ($matched && count($pattern) > 1) {
			foreach (array_splice($pattern, 1) as $name => $value) {
				if (!isset ($_GET[$name]) || $_GET[$name] != $value)
					return false;
			}
			return true;
		} else
			return $matched;
	}
}


?>